import React from 'react';
import { Form, Input, Button, Card, Row, Col, Spin } from 'antd';
import { useRequest } from 'ahooks';
import { signin } from '@/services/user';
import {useModel,history} from '@umijs/max'
import {decode} from 'jsonwebtoken';
export default function Page() {
  const {initialState,setInitialState} = useModel('@@initialState');
  //data请求的返回值 loading请求期间为true,请求结束后为false,run手工触发请求
  const { loading, run } = useRequest(signin, {
    manual: true,//不要自动请求，我要手工触发请求
    onSuccess(tokens) {//成功的回调
      try{
        //因为返回的tokens可能是不合法的，可以加一个try catch
        //为了避免丢失，所以把token也保存在了local里里一份
        localStorage.setItem('tokens',JSON.stringify(tokens));
        const {access_token} = tokens;
        const {currentUser} = decode(access_token);
        //当登录成功之后把当前用户保存到了内存中，刷新之后这些信息会丢失
        setInitialState({currentUser);
      }catch(error){
        console.error('解析tokens失败');
        localStorage.removeItem('tokens');
      }
    }
  });
  //监听 initialState的变化，当 setInitialState({currentUser});的时候initialState发生变化
  React.useEffect(()=>{
    if(initialState?.currentUser){
      history.push('/');
    }
  },[initialState]);
  const onFinish = (values) => {
    run(values);
  }
  const onFinishFailed = (errorInfo) => {
    console.error(errorInfo)
  }
  return (
    <Row style={{ marginTop: '20%' }}>
      <Col offset={8} span={8}>
        <Card title="请登录">
          <Spin spinning={loading}>
            <Form
              labelCol={{ span: 8 }}
              wrapperCol={{ span: 18 }}
              onFinish={onFinish}
              onFinishFailed={onFinishFailed}
            >
              <Form.Item
                label="用户名"
                name="username"
                rules={[{ required: true, message: '请输入用户名' }]}
              >
                <Input />
              </Form.Item>
              <Form.Item
                label="密码"
                name="password"
                rules={[{ required: true, message: '请输入密码' }]}
              >
                <Input.Password />
              </Form.Item>
              <Form.Item wrapperCol={{ offset: 8, span: 16 }}>
                <Button type='primary' htmlType='submit'>提交</Button>
              </Form.Item>
            </Form>
          </Spin>

        </Card>

      </Col>
    </Row>
  );
}
